package com.integrationpath.mengine.util;

import java.io.IOException;
import java.sql.ResultSet;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.List;
import java.util.Locale;
import java.util.Properties;
import java.util.ResourceBundle;

import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang.StringEscapeUtils;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import com.integrationpath.mengine.dao.UtilityDao;

public class DbResourceBundle extends ResourceBundle {
	private Properties properties;

	public DbResourceBundle(Properties inProperties) {
		properties = inProperties;
	}

	@Override
	@SuppressWarnings(value = { "unchecked" })
	public Enumeration<String> getKeys() {
		return properties != null ? ((Enumeration<String>) properties
				.propertyNames()) : null;
	}

	@Override
	protected Object handleGetObject(String key) {
		return properties.getProperty(key);
	}

	public static ResourceBundle.Control getMyControl(final HttpServletRequest request) {
		return new ResourceBundle.Control() {
			UtilityDao utilityDao  = (UtilityDao) getSpringContext(request).getBean("utilityDao");

			@Override
			public List<String> getFormats(String baseName) {
				if (baseName == null) {
					throw new NullPointerException();
				}
				return Arrays.asList("db");
			}

			@Override
			public ResourceBundle newBundle(String baseName, Locale locale,
					String format, ClassLoader loader, boolean reload)
					throws IllegalAccessException, InstantiationException,
					IOException {
				if ((baseName == null) || (locale == null) || (format == null)
						|| (loader == null))
					throw new NullPointerException();
				ResourceBundle bundle = null;
				if (format.equals("db")) {
					Properties p = new Properties();
					
//					StringBuilder query = new StringBuilder();
//					query.append("select label, value from " + StringEscapeUtils.escapeSql(baseName));
//					if (locale != null) {
//						if (!locale.getCountry().equals("")) {
//							query.append("_" + escapeSql(locale.getCountry()));
//						}
//						if (!locale.getLanguage().equals("")) {
//							query.append("_" + escapeSql(locale.getLanguage()));
//						}
//						if (!locale.getVariant().equals("")) {
//							query.append("_" + escapeSql(locale.getVariant()));
//						}
//					}
					
					ResultSet rs = null;
					try {
						StringBuilder query = new StringBuilder();
						query.append("select label, value from i18n where bundle='"
										+ StringEscapeUtils.escapeSql(baseName)
										+ "' ");
						if (locale != null) {
							if (!locale.getCountry().equals("")) {
								query.append("and country='"
												+ escapeSql(locale.getCountry())
												+ "' ");
							}
							if (!locale.getLanguage().equals("")) {
								query.append("and language='"
										+ escapeSql(locale.getLanguage())
										+ "' ");
							}
							if (!locale.getVariant().equals("")) {
								query
										.append("and variant='"
												+ escapeSql(locale.getVariant())
												+ "' ");
							}
						}
						
						rs = utilityDao.executeQuery(query.toString());
						while (rs.next()) {
							p.setProperty(rs.getString(1), rs.getString(2));
						}
					} catch (Exception e) {
						e.printStackTrace();
						throw new RuntimeException("Can not build properties: "
								+ e);
					}
					bundle = new DbResourceBundle(p);
				}
				return bundle;
			}

			private String escapeSql(String variant) {
				return variant;
			}

			@Override
			public long getTimeToLive(String baseName, Locale locale) {
				return 1000 * 60 * 30;
			}

			@Override
			public boolean needsReload(String baseName, Locale locale,
					String format, ClassLoader loader, ResourceBundle bundle,
					long loadTime) {
				return true;
			}
		};
	}

	private static WebApplicationContext getSpringContext(HttpServletRequest request) {
		return WebApplicationContextUtils.getWebApplicationContext(request
				.getSession().getServletContext());
	}
}